/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package udpUnitAdapt;
import java.awt.Color;
import java.io.*;
import java.net.*;
import java.util.*;

/**
 *
 * @author axelsben
 */
public class udpServer{

    private int useSocket = 4774;
    private javax.swing.JTextArea jta = null;
    private String useAddress = "localhost";
    private boolean logging = false;

    private String clientAddress = "";

    public String getClientAddress()
    {
        return clientAddress;
    }

    public void setLogging(boolean bool)
    {
        logging = bool;
    }

    public void setTA(javax.swing.JTextArea jtxta)
    {
        jta = jtxta;
    }

    public void setSocket(int socket)
    {
        useSocket = socket;
    }

    public int getSocket()
    {
        return useSocket;
    }

    public void setAddress(String address)
    {
        useAddress = address;
    }

    public String getAddress()
    {
        return useAddress;
    }


    public byte[] receive(DatagramSocket socket) {

        try {
            byte[] buf = new byte[8096];

           // receive request
           DatagramPacket packet = new DatagramPacket(buf, buf.length);
           socket.receive(packet);
           clientAddress = packet.getAddress().getHostAddress();
           if(logging)
           {
                jta.setSelectionStart(jta.getText().length());
                jta.setSelectionEnd(jta.getText().length()+1);
                jta.replaceSelection("/ur:" + new String(buf,0,buf.length));
                if(jta.getText().length() > 25000)
                {
                    int rm = jta.getText().length() - 25000;
                    jta.setSelectionStart(0);
                    jta.setSelectionEnd(rm);
                    jta.replaceSelection("");
                }
                jta.setSelectionStart(jta.getText().length());
                jta.setSelectionEnd(jta.getText().length()+1);
            }
            return new String(packet.getData(), 0, packet.getLength()).getBytes();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
